package com.extremelylargepackage;

import java.io.InputStream;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import android.content.res.AssetManager;
import android.util.Log;

import com.extremelylargepackage.entity.BeamWeapon;
import com.extremelylargepackage.entity.EntityFactory;
import com.extremelylargepackage.entity.Projectile;
import com.extremelylargepackage.entity.EntityFactory.EntityType;
import com.extremelylargepackage.entity.Weapon;

public class WeaponParser 
{
	public static HashMap<String, Weapon> loadWeapons(AssetManager a)
	{
		HashMap<String, Weapon> weapons = new HashMap<String, Weapon>();
		String[] paths = null;
		try 
		{
			paths = a.list("weapon");
			for(int i = 0; i < paths.length; i++)
			{
				Log.d("", paths[i]);
				InputStream stream = a.open("weapon/" + paths[i]);
				Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(stream);
				doc.getDocumentElement().normalize();
				
				Element element = (Element) doc.getElementsByTagName("Weapon").item(0);
				String name = element.getAttribute("name");
				String wType = element.getAttribute("type");
				Weapon weapon;
				if("beam".equalsIgnoreCase(wType))
					weapon = (BeamWeapon) EntityFactory.createEntity(EntityType.beamWeapon);
				else
					weapon = (Weapon)EntityFactory.createEntity(EntityType.weapon);
				
				float fireRate = Float.parseFloat(element.getAttribute("fireRate"));
				Projectile proj = GameResources.getProjectile(element.getAttribute("projectile"));
				String bl = element.getAttribute("beamLength");
				int beamLength = 0;
				if(bl != null && !bl.equals(""))
					beamLength = Integer.parseInt(bl);
				
				EntityFactory.setWeaponProperties(weapon, fireRate, proj);
				if(weapon instanceof BeamWeapon)
					EntityFactory.setBeamWeaponProperties((BeamWeapon)weapon, beamLength);
				EntityFactory.setName(weapon, name);
				weapons.put(name, weapon);
			}
		}
		catch(Exception e)
		{
			Log.e("ERROR PARSING WEAPON", "", e);
		}
		return weapons;
	}
}
